import axios from 'axios';
import { configService } from '../../services/config-service';

export class BatchConvert {
  constructor() {
    this.selectedFiles = [];
    this.sourceFormat = '';
    this.targetFormat = '';
    this.isConverting = false;
    this.convertProgress = 0;
    this.convertResults = [];
    this.errorMessage = '';
    this.isLoading = true;
    
    this.formats = [];
    this.conversionOptions = {
      addTitle: false,
      preserveLineBreaks: true,
      addPageBreaks: false
    };

    this.init();
  }

  async init() {
    try {
      await configService.loadConfig();
      this.formats = configService.getSupportedFormats();
      this.isLoading = false;
    } catch (error) {
      console.error('初始化失败:', error);
      this.errorMessage = '初始化失败，请刷新页面重试';
      this.isLoading = false;
    }
  }

  onFilesSelected(event) {
    const files = Array.from(event.target.files);
    this.validateAndSetFiles(files);
  }

  validateAndSetFiles(files) {
    const validFiles = [];
    const errors = [];

    files.forEach(file => {
      // 检查文件大小
      if (file.size > configService.getMaxFileSize()) {
        errors.push(`${file.name}: 文件大小超过限制`);
        return;
      }

      // 检查文件格式
      const extension = file.name.split('.').pop().toLowerCase();
      if (!configService.isFormatSupported(extension)) {
        errors.push(`${file.name}: 不支持的文件格式`);
        return;
      }

      validFiles.push({
        file: file,
        name: file.name,
        size: configService.formatFileSize(file.size),
        format: extension,
        status: 'pending'
      });
    });

    this.selectedFiles = validFiles;
    
    if (validFiles.length > 0) {
      this.sourceFormat = validFiles[0].format;
    }

    if (errors.length > 0) {
      this.errorMessage = errors.join('\n');
    } else {
      this.errorMessage = '';
    }
  }

  onDragOver(event) {
    event.preventDefault();
    event.dataTransfer.dropEffect = 'copy';
  }

  onDrop(event) {
    event.preventDefault();
    const files = Array.from(event.dataTransfer.files);
    this.validateAndSetFiles(files);
  }

  removeFile(index) {
    this.selectedFiles.splice(index, 1);
    if (this.selectedFiles.length === 0) {
      this.sourceFormat = '';
      this.targetFormat = '';
    }
  }

  getAvailableTargetFormats() {
    if (!this.sourceFormat) return [];
    const availableFormats = configService.getAvailableTargetFormats(this.sourceFormat);
    return this.formats.filter(format => availableFormats.includes(format.value));
  }

  async convertFiles() {
    if (this.selectedFiles.length === 0 || !this.sourceFormat || !this.targetFormat) {
      this.errorMessage = '请选择文件和转换格式';
      return;
    }

    this.isConverting = true;
    this.convertProgress = 0;
    this.errorMessage = '';
    this.convertResults = [];

    try {
      const totalFiles = this.selectedFiles.length;
      
      for (let i = 0; i < totalFiles; i++) {
        const fileItem = this.selectedFiles[i];
        fileItem.status = 'converting';

        try {
          const formData = new FormData();
          formData.append('file', fileItem.file);
          formData.append('source_format', this.sourceFormat);
          formData.append('target_format', this.targetFormat);
          formData.append('options', JSON.stringify(this.conversionOptions));

          const response = await axios.post(`${configService.getApiBaseUrl()}/convert`, formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            },
            responseType: 'blob'
          });

          // 创建下载链接
          const blob = new Blob([response.data]);
          const url = window.URL.createObjectURL(blob);
          const originalName = fileItem.file.name.split('.')[0];
          const downloadName = `${originalName}_converted.${this.targetFormat}`;

          this.convertResults.push({
            originalName: fileItem.name,
            downloadUrl: url,
            filename: downloadName,
            size: configService.formatFileSize(blob.size),
            status: 'success'
          });

          fileItem.status = 'completed';

        } catch (error) {
          console.error(`转换文件 ${fileItem.name} 失败:`, error);
          this.convertResults.push({
            originalName: fileItem.name,
            error: error.response?.data?.error || '转换失败',
            status: 'error'
          });
          fileItem.status = 'error';
        }

        this.convertProgress = Math.round(((i + 1) / totalFiles) * 100);
      }

    } catch (error) {
      this.errorMessage = '批量转换过程中发生错误';
      console.error('批量转换错误:', error);
    } finally {
      this.isConverting = false;
    }
  }

  downloadResult(result) {
    if (result.downloadUrl) {
      const link = document.createElement('a');
      link.href = result.downloadUrl;
      link.download = result.filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }

  downloadAllResults() {
    const successResults = this.convertResults.filter(r => r.status === 'success');
    successResults.forEach(result => {
      setTimeout(() => this.downloadResult(result), 100);
    });
  }

  resetForm() {
    this.selectedFiles = [];
    this.sourceFormat = '';
    this.targetFormat = '';
    this.convertResults = [];
    this.errorMessage = '';
    this.convertProgress = 0;
    
    // 重置文件输入
    const fileInput = document.getElementById('batchFileInput');
    if (fileInput) {
      fileInput.value = '';
    }
  }

  getFormatIcon(format) {
    const formatObj = this.formats.find(f => f.value === format);
    return formatObj ? formatObj.icon : '📄';
  }

  getFormatLabel(format) {
    const formatObj = this.formats.find(f => f.value === format);
    return formatObj ? formatObj.label : format.toUpperCase();
  }

  getTotalFileSize() {
    const totalBytes = this.selectedFiles.reduce((sum, file) => sum + file.file.size, 0);
    return configService.formatFileSize(totalBytes);
  }

  getSuccessCount() {
    return this.convertResults.filter(r => r.status === 'success').length;
  }

  getErrorCount() {
    return this.convertResults.filter(r => r.status === 'error').length;
  }
} 